/*
 * Middleware
 * Copyright (C) 2010/11
 * Riccardo Pulvirenti, Giuseppe Ravidà, Andrea Tino
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANDABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses
 */

/*!
 * File: workerdescriptor_manager_proxy.cpp
 */

#include <boost/asio.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/thread.hpp>
#include <boost/lexical_cast.hpp>

#include "workerdescriptor_manager_proxy.hpp"

using namespace middleware;

//-----------------------------------------------------------------------------
// Constructors and destructor
/* Default private constructor */
WorkerDescriptorManagerProxy::WorkerDescriptorManagerProxy() {
	this->_config.ip_bind_disc = "127.0.0.1"; /* Not used */
	this->_config.port_bind_disc = "0";
}
/* Private parameter constructor */
WorkerDescriptorManagerProxy::WorkerDescriptorManagerProxy(WDProxyConfig conf) {
	this->_config.ip_bind_disc = conf.ip_bind_disc; /* Not used */
	this->_config.port_bind_disc = conf.port_bind_disc;
}
/* Destructor */
WorkerDescriptorManagerProxy::~WorkerDescriptorManagerProxy() {

}
//-----------------------------------------------------------------------------
// Public members
/* Receiving task */
WorkerDescriptor WorkerDescriptorManagerProxy::recv_workerdescriptor()
		throw(ProxyException) {
	using boost::asio::ip::tcp;
	int port = boost::lexical_cast<int>(this->_config.port_bind_disc);
	boost::asio::io_service io_s;
	try {
		tcp::acceptor wd_acceptor(io_s, tcp::endpoint(tcp::v4(), port));
		tcp::iostream wd_stream;
		WorkerDescriptor wd;
		wd_acceptor.accept(*(wd_stream.rdbuf())); /* Accepting */
		boost::archive::binary_iarchive ia(wd_stream);
		ia >> wd; /* Here I have the worker descriptor */
		wd_stream.close();
		return wd;
	} catch(std::exception& e) {
		throw ProxyException(std::string("Error in proxy: ") + e.what());
	}
}
